import { showFailToast, showNotify } from 'vant';
import { ref } from 'vue';

import { deserialize } from '@/plugins/reflect-metadata';

import { updateAvatar, uploadFile } from '../api';
import UploadFile, { UpdateAvatar, UploadFileResponse } from '../models/UploadFile';

const useUploadFile = () => {
  const params = ref<UploadFile>(new UploadFile());
  const paramsAvatar = ref<UpdateAvatar>(new UpdateAvatar());
  const loading = ref(false);
  const state = ref<UploadFileResponse>(new UploadFileResponse());

  const handleUploadFile = async () => {
    try {
      loading.value = true;
      const { data } = await uploadFile(params.value);
      const resultData = deserialize(data, UploadFileResponse);
      state.value = resultData;
    } catch (error) {
      //
    } finally {
      loading.value = false;
    }
  };

  const beforeImgUpload = (file: any) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJPG) {
      showFailToast('You can only upload JPG file!');
    }
    return isJPG;
  };

  const handleUpdateAvatar = async () => {
    try {
      loading.value = true;
      paramsAvatar.value.avatar = state.value.url;
      await updateAvatar(paramsAvatar.value);
      showNotify({ message: '上传成功', type: 'success' });
    } catch (error) {
      //
    } finally {
      loading.value = false;
    }
  };

  return {
    params,
    loading,
    handleUploadFile,
    handleUpdateAvatar,
    beforeImgUpload,
  };
};

export default useUploadFile;
